/**
 * Created by Administrator on 2016/12/5.
 */
! function() {
  $(function() {
    layui.use(['layer', 'form'], function(){
      var layer = layui.layer
      ,form = layui.form;
    });
    var tableData = [];
    var custNameLike = $("#searchInput").val();
    var currentPage = 1;
    var systems = [];
    function getList(curr, type, pagination, angu) {
      var vm = {};
      // 司法协助请求
      $.ajax({
        url: '/cloud/kcloudAccount/list',
        type: "POST",
        dataType: "json",
        data: {
          size: type,
          page: curr,
          userName: angu.custNameLike || ''
        },
        error: function() {
          vm.toggle = 3;
          $('#tableBody').html(template('tableTpl', {
            vm: vm
          }));
        }
      }).done(function(data) {
        if (data.code == '0') {
          if (data.data.content.length > 0) {
            vm.toggle = 2;
            vm.infoList = data.data.content;
            vm.totalRow = data.data.total;
            tableData = data.data.content;
            laypage({
              cont: pagination, //容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
              pages: Math.ceil(data.data.total / type), //通过后台拿到的总页数
              curr: curr || 1, //当前页
              first: 1, //将首页显示为数字1,。若不显示，设置false即可
              last: Math.ceil(data.data.total / type), //将尾页显示为总页数。若不显示，设置false即可
              skin: '#0299ff',
              jump: function(obj, first) { //触发分页后的回调
                if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                  currentPage = obj.curr;
                  getList(obj.curr, type, pagination, {
                    custNameLike: $("#searchInput").val()
                  });
                }
              }
            });
          } else {
            vm.toggle = 3;
          }
        }else if (data.code === '-1'){
          layer.msg('登录超时,即将跳转登录页')
          location.href = '/login';
        } else {
          vm.toggle = 3;
        }
        $('#tableBody').html(template('tableTpl', {
          vm: vm
        }));
      });
    }

    // 删除账户
    function deleteRowe(rowData) {
      var index = layer.confirm('确定要删除 ' + rowData.userName +' 账号吗？', {
        btn: ['确定', '取消'] //按钮
      }, function() {
        $.ajax({
          url: '/cloud/kcloudAccount/delete',
          type: "POST",
          dataType: "json",
          data: {
            id: rowData.id
          },
          error: function() {}
        }).done(function(data) {
          if (data.code === '0') {
            layer.msg('删除成功');
            getList(currentPage, 10, $("#pagination_page"), {
              custNameLike: custNameLike
            });
          } else if (data.code === '-1'){
            layer.msg('登录超时,即将跳转登录页')
            location.href = '/login';
          } else {
            layer.msg(data.msg);
          }
        })
      }, function() {
        layer.close(index);
      })
    }


    function addAndUpdate(url, data) {
      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: data,
        error: function() {}
      }).done(function(data) {
        if (data.code === '0') {
          getList(currentPage, 10, $("#pagination_page"), {
            custNameLike:  $("#searchInput").val()
          });
          $('#account').modal('hide')
        } else if (data.code === '-1'){
          layer.msg('登录超时,即将跳转登录页')
          location.href = '/login';
        } else {
          layer.msg(data.msg);
        }
      })
    }

    getList(1, 10, $("#pagination_page"), {
      custNameLike: custNameLike
    });

    $('#searchBtn').on('click', function() {
      getList(1, 10, $("#pagination_page"), {
        custNameLike: $("#searchInput").val()
      })
    })
    $('#addAccountBtn').on('click', function() {
      $('#accountFormWrap').html(template('accontFormTpl', {
        selectData: systems,
        form: {},
        title: '新增账户'
      }));
      $('#account').modal('show')
      $('#accountForm').bootstrapValidator({
      　 feedbackIcons: {
  　　　　　　　　valid: 'glyphicon glyphicon-ok',
  　　　　　　　　invalid: 'glyphicon glyphicon-remove',
  　　　　　　　　validating: 'glyphicon glyphicon-refresh'
  　　　　　　　},
          fields: {
            userName: {
                  message: '用户名验证失败',
                  validators: {
                      notEmpty: {
                          message: '请输入用户账号'
                      }
                  }
              },
              customer: {
                  validators: {
                      notEmpty: {
                          message: '请输入客户名称'
                      }
                  }
              },
              contacts: {
                  validators: {
                      notEmpty: {
                          message: '请输入联系人名称'
                      }
                  }
              },
              contactsPhone: {
                  validators: {
                      notEmpty: {
                          message: '请输入联系方式'
                      }
                  }
              },
              bussinessSystem: {
                  validators: {
                      notEmpty: {
                          message: '请选择业务系统'
                      }
                  }
              },
          }
      }).on('success.form.bv', function(e) {
        
        // Prevent form submission
        e.preventDefault();
        
        // Get the form instance
        var $form = $(e.target);

        // Get the BootstrapValidator instance
        var bv = $form.data('bootstrapValidator');
        if ($('#myModalLabel').html() === '新增账户') {
          url = '/cloud/kcloudAccount/add'
        } else {
          url = '/cloud/kcloudAccount/update';
        }
        addAndUpdate(url, getFormField('#accountForm'))
      })
    })
    $('#tableBody').on('click', '[data-handle]', function(e) {
      var handleType = $(this).data('handle');
      var tr = $(this).parents('tr')[0];
      var rowIndex = $('#tableBody tr').index(tr);
      var rowData = tableData[rowIndex]
      if (handleType === 'update') {
        console.log('update')
        $('#accountFormWrap').html(template('accontFormTpl', {
          selectData: systems,
          form: rowData,
          title: '修改账户'
        }));
        $('#account').modal('show')
      } else if (handleType === 'delete') {
        deleteRowe(rowData)
      }
    });
    getSystemList();
    function getSystemList() {
      $.ajax({
        url: '/sso/ssoServiceSystem/list',
        type: "POST",
        dataType: "json",
        data: {
        },
        error: function() { layer.msg('服务器错误，获取系统信息失败！')}
      }).done(function(data) {
        data = JSON.parse(data)
        if (data.code === '0') {
          systems = data.data;
          store.set('system', systems)
        } else if (data.code === '-1'){
          layer.msg('登录超时,即将跳转登录页')
          location.href = '/login';
        } else {
          layer.msg(data.msg);
        }
      })
    }
    /**
     * 获取表单下面的所有name
     * @param {*string} formId form表单id
     * @return {*object} result 所有name元素的组件 [{name: 123}, {age: 18}]
     */
    function getFormField(formId) {
      var form = $(formId);
      var result = {};
      var field = form.find('[name]');
      field.each(function(index, item) {
        var $item = $(item);
        result[$item.attr('name')] = $item.val();
      })
      return result;
    }
  })
}();
